/**
 * 
 */
package com.obradovicnjegovan.webprodavnica.pages;

import java.util.HashSet;

import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.hibernate.annotations.CommitAfter;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.Request;

import com.obradovicnjegovan.webprodavnica.controller.ControllerAL;
import com.obradovicnjegovan.webprodavnica.entities.Korpa;
import com.obradovicnjegovan.webprodavnica.entities.Narudzbenica;
import com.obradovicnjegovan.webprodavnica.entities.OdabranProizvod;

/**
 * @author njegovan
 *
 */
public class Checkout {
	@Inject
	private ControllerAL controllerAL;
	@Persist
	private Narudzbenica narudzbenica;
	@Inject
    private Request request;
	
	public Narudzbenica getNarudzbenica() {
		return narudzbenica;
	}
	public void setNarudzbenica(Narudzbenica narudzbenica) {
		this.narudzbenica = narudzbenica;
	}


	@CommitAfter
	public Object onConfirm(){
		try {
			controllerAL.sacuvajNarudzbenicu(getNarudzbenica());
			controllerAL.setRequest(request);
			Korpa korpa = new Korpa();
			korpa.setOdabraniProizvodi(new HashSet<OdabranProizvod>());
			controllerAL.sacuvajKorpu(korpa);
			controllerAL.preuzmiKorpu(korpa);
			return Index.class;
		} catch (Exception e) {
			// TODO: handle exception
		}
		return null;
	}
	
	public Object onDecline(){
		return Order.class;
	}
	
	@Property
	private OdabranProizvod op;
	public String formatCena(double cena){
		return controllerAL.formatDouble(cena);
	}
	
	public double getCenaOd(){
		return op.getProizvod().getCena()*op.getKolicina();
	}
	
	public double getUkupnaCena(){
		double ukupnaCena = 0;
		try {
			for (OdabranProizvod od : controllerAL.getKorpa().getOdabraniProizvodi()) {
				ukupnaCena = ukupnaCena + (od.getProizvod().getCena()*od.getKolicina());
			}
			return  ukupnaCena;
		} catch (Exception e) {
			// TODO: handle exception
		}
		return 0;
	}
}